Java Web Service JAX WS Tool - java

I have created the web service and in that i am coonecting the database and access the information form that but couldn't successful.
/
**
*
*/
package com.xxxxx.www.testprocess;
import javax.jws.*;
import java.sql.*;
import java.util.*;
/**
* #author Suryasol6
*
*/
#WebService(name="TestProcess",targetNamespace ="http://www.example.org/TestProcess")
public class TestProcess {
private Connection connect = null;
private Statement statement = null;
private PreparedStatement ps = null;
private ResultSet rs = null;
private static final String CONNECTION_URL = "jdbc:mysql://localhost:3306/java_test?user=root&;password=";
#WebMethod(action="http://www.example.org/TestProcess/TestLogin")
#WebResult(name="TestLoginresponse")
public String TestLogin(#WebParam(name="name")
String name,#WebParam(name="password")
String password)
{
try
{
Class.forName("com.mysql.jdbc.Driver").newInstance();
}
catch(Exception e)
{
return "fail here";
}
return "pass";
}
}
I can publish the web service but when i try to connect the web service with parametes, it fails to load the jdbc driver.
But when i try to run this file as seperate this worked.
Can anybody help me??

Do you have the MySQL driver jar in the JBoss server lib directory? It should go in:
<JBoss_home>/server/default/lib
When you run it manually you may be specifying the classpath to include the jar, but JBoss needs it there.

Related

Android Crash When Connecting to SQL Server

I am having an issue with an app I am testing. I am using Android Studio and JTDS 1.3.1. I am just trying to test connecting to the database. The end product will be a label application only used within our company on our network. I have tried Microsoft's JDBC driver as well, with no success. The app crashes when it tries to create a connection. I have added JTDS as a module and a dependency. The app is just a button that calls a static method and a text view to display an error or success if it works. If I don't load the database driver I do get a SqlException error for no suitable driver found. When I do load the driver the app closes with no error reported.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBHelper {
public static String checkConnection() {
String message;
String username = "username";
String password = "password";
String connectionURL = "jdbc:jtds:sqlserver://server-name/database-name";
try (Connection connection = DriverManager.getConnection(connectionURL, username, password)) {
message = "Success";
return message;
} catch (SQLException sqle) {
message = sqle.getMessage();
return message;
}
}
}
I know it is too late but try using jtds 1.2.7 version jar

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.

How to import JDBC driver into Dynamic Web Project?

I have a local MySQL database. When I created a simple Java project, with one class which contained only main, I successfully retrieved some data from the database using JDBC connector jar, imported with Build path -> Add external jars, and it worked perfectly.
Then I tried to use a similar approach, but now in a Dynamic Web Project, in which I am using Servlets, but I get java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/ePay.
I have been looking for several hours into the answers of similar questions, and here is where I have tried to put the JDBC MySQL connector so far:
Directly into Java Resources folder
Into lib folder which is within Java Resources
Into WebContent/WEB-INF/lib/
Do I need web.xml or context.xml? I read a tutorial in which they were used, tried to implement the explained example, but I still had the same problem.
I am working on Linux Mint 17, using Tomcat 7 into Eclipse IDE.
Here is the photo of my project structure:
Here are the relevant classes:
package dbObjects;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Entity {
protected Connection getConnection() throws SQLException {
String pass = "mypass";
String userDB = "root";
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/ePay", userDB, pass);
return conn;
}
protected ResultSet getResultSet(String sql) throws SQLException {
Connection conn = getConnection();
Statement st = conn.createStatement();
return st.executeQuery(sql);
}
}
The user class:
package dbObjects;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;
public class User extends Entity {
private long idUser;
private String userName;
private String pass;
private String fullName;
private String email;
private Date dateOfBirth;
private String address;
public User(long idUser, String userName, String pass, String fullName,
String email, Date dateOfBirth, String address) {
super();
this.idUser = idUser;
this.userName = userName;
this.pass = pass;
this.fullName = fullName;
this.email = email;
this.dateOfBirth = dateOfBirth;
this.address = address;
}
public User(long idUser) throws SQLException {
super();
this.idUser = idUser;
setUserById(idUser);
}
private void setUserById(long idUser) throws SQLException {
ResultSet resultSet = getResultSet("SELECT * FROM User WHERE idUser = " + idUser);
while(resultSet.next()) {
System.out.println(resultSet.getInt("idUser"));
userName = resultSet.getString("username");
pass = resultSet.getString("pass");
fullName = resultSet.getString("fullname");
email = resultSet.getString("email");
dateOfBirth = resultSet.getDate("dateOfBirth");
address = resultSet.getString("address");
}
}
#Override
public String toString() {
return userName;
}
}
And the servlet which I am trying to run:
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dbObjects.User;
/**
* Servlet implementation class HomeServlet
*/
#WebServlet(description = "Home page shown to user", urlPatterns = { "/HomeServlet" })
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HomeServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
User user = null;
try {
user = new User(1);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
PrintWriter pw = response.getWriter();
pw.println(user);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
There are two ways to use and reference a jar file in an eclipse project.
One is at compile time and for compilation purposes. To make your project compile, you need to add your required libraries in the classpath. In eclipse, right click to your project, hover on 'Build Path', then select 'Configure Build Path'. In the dialog go to 'Libraries' tab and there you can see which jars/libraries you have. If you need to add more, you can use the buttons at the right side of the dialog. There you should select 'Add external jars' and select the MySql JDBC Driver from your file system.
The other one is at run time. This is when you deploy your web application to an application server. Now everytime your application needs to load a class from an external jar, it will look for the jar in the application server's class loader. The classloader conatins the paths to the available jar files in your application server, in configured resources and in your deployed application in the WEB-INF/lib/ folder. You can configure which place the classloader will check first.
In your very specific case, you need to add the MySQL JDBC Driver in any of classloader paths (since I asume your project compiles already) so you can either add the jar to Tomcat's /lib directory or to your application's /WEB-INF/lib/ directory. After that just redeploy or restart tomcat and you should be able to use MySQL JDBC connections.
UPDATE:
Also, when using a DriverManager interface to create a JDBC Connection, remember to always create an instance of your JDBC driver first in order to load it into your Classloader. You can see this in the MySQL JDBC Driver documentation. Ej:
Class.forName("com.mysql.jdbc.Driver").newInstance();
Call this line before using DriverManager.getConnection(...) and you should now be able to create and use your JDBC Connections.
Your mysql jdbc driver should be placed into your tomcat's directory:
catalina_base/webapps/app_name/WEB-INF/lib/
Make sure to start/restart your server after placing your new mysql jdbc driver jar file there.
just place your driver jar file into WEB-INF/lib folder.

class not found exception com.mysql.jdbc.driver [duplicate]

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 7 years ago.
File structure of my project is:
-src
|
-pkg
|
-CoreServlet.java(servlet)
-Main.java
-Core.java(jdbc code is here)
core.java class:
package com.pkg;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class core{
private Connection connect = null;
private Statement statement =null;
private PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
String qwerty;
public void readDataBase() {
String userName = "ansh";
String password = "12345";
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager.getConnection("jdbc:mysql://localhost/glbitm", userName,password);
statement = connect.createStatement();
resultSet = statement.executeQuery("select * from teachers");
resultSet.next();
qwerty = resultSet.getString(1);
} catch (Exception e) {
System.out.println(e);
}
}
}
coreServlet.java class :
package com.pkg;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class coreServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException{
core dao = new core();
dao.readDataBase();
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html>");
pw.println("<head><title>Hello World</title></head>");
pw.println("<div>"+dao.qwerty+"</div>");
pw.println("<body>");
pw.println("<h1>Hello World</h1>");
pw.println("</body></html>");
}
}
When I am accessing dao.qwerty in my coreServlet.java in my tomcat server. I am getting class not found exception com.mysql.jdbc.driver and value of dao.qwerty is printed as null. Where I am doing wrong ?
You need to add the mysql connector in classpath.
http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.1.4/mysql-connector-java-5.1.4.jar
This connector jar acts as a mediator between database and the application for the flow of data. You can extract the class files from jar and see the details.
The java.lang.ClassNotFoundException is thrown when your code attempts to execute the following line
Class.forName("com.mysql.jdbc.Driver").newInstance();
This is a checked exception which always needs to be either caught inside a try/catch or if try/catch is not implemented, then this exception needs to be declared in the method.
There have been multiple resolutions provided in this thread, but from my experience if you are able to connect to your database from eclipse using data source explorer, then most likely reason is "mysql-connector-java-5.1.28-bin.jar" is not copied into the your tomcat's lib directory.
The mysql connector for java can be downloaded from http://dev.mysql.com/downloads/connector/j/
You have not set the mysql-connector in your path.Set that first and everything else will be done
What is JConnector ?
Java does not know SQL so every statement you want to execute using the sql driver will get converted to sql constructs and the result that is returned my mysql is also converted into java understandable constructs.
hope it helps

Error on testing connection with Mysql Database

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
//This class is for testing connection with mysql database
class JDBCTest {
// path to database is stored in string url
private static final String url = "jdbc:mysql://localhost";
// username is stored in string root
private static final String user = "root"; //username
// password is stored in string password
private static final String password = "swapnil";//password
public static void main(String args[]) {
try {
//i have stored driver in c:\javap\
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url, user, password);
System.out.println("Success");
} catch (Exception e) {
System.out.println("hi");
e.printStackTrace();
}
}
}
whenever I try to run this program I get the exception
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
I am using mysql database my operating system is windows 7 64 bit. I have included the mysql-connector-java-5.1.22-bin in jdk/jre/lib/ext I have also set up the CLASSPATH Environment variable but nothing work me out
First of all, you should not put anything under the JDK's jre/lib/ext directory.
Instead, use the -cp option when launching your application, and make sure to have the jar of the driver (and not the bin directory) in the classpath:
java -cp mysql-xx.jar;... com.foo.bar.JDBCTest
The URL is incomplete use:
private static final String url = "jdbc:mysql://localhost:3306/databasename";
also as #JB Nizet mentioned do not put jars in jdk's lib.

Categories

Resources